package com.br.sistema.Util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

import com.br.sistema.conexao.HibernateUtil;

@org.hibernate.annotations.Filter(name = "conexaoFilter")
public class ConexaoHibernateFilter implements Filter{

	private SessionFactory sessionFactory;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		try{
			
			sessionFactory.getCurrentSession().beginTransaction();
			chain.doFilter(servletRequest, servletResponse);
			sessionFactory.getCurrentSession().getTransaction().commit();
			sessionFactory.getCurrentSession().close();
		
		}catch(Throwable e){
			try {
				e.printStackTrace();
				if(sessionFactory.getCurrentSession().getTransaction().isActive()){
					sessionFactory.getCurrentSession().getTransaction().rollback();
				}
			
			} catch (Throwable t) {
				// TODO: handle exception
				t.printStackTrace();
			}
			
			throw new ServletException();
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		sessionFactory = HibernateUtil.getSession();
	}

}
